from fastapi import APIRouter, HTTPException
import sqlite3  # 假设使用SQLite；替换为您的数据库
from schemas import SQLQuery, QueryResponse

router = APIRouter(prefix="/data", tags=["data"])

@router.post("/query", response_model=QueryResponse)
async def execute_query(query: SQLQuery):
    if not query.sql.strip().upper().startswith("SELECT"):
        raise HTTPException(status_code=400, detail="Only SELECT statements are allowed.")
    
    try:
        conn = sqlite3.connect("your_database.db")  # 替换为实际DB
        cursor = conn.cursor()
        cursor.execute(query.sql)
        data = cursor.fetchall()
        columns = [desc[0] for desc in cursor.description]
        result = [dict(zip(columns, row)) for row in data]
        conn.close()
        return QueryResponse(success=True, count=len(result), data=result)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))
    


    